package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("ExpireRestController")
public class ExpireRestController extends CmiEmaController {

	/**
	 * Create a new Expire entity
	 * 
	 */
	@RequestMapping(value = "/newExpire", method = RequestMethod.POST)
	@ResponseBody
	public Object newExpire(@RequestBody Expire expire) {
		expireService.saveExpire(expire);
		return JSONObject.parse(cmiPsonService.toJsonString(expireDAO.findExpireByPrimaryKey(expire.getId()), 2));
	}

	@RequestMapping(value = "/restNewExpire", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewExpire(@RequestBody String expireJson) {
		Expire expire = new Gson().fromJson(expireJson, Expire.class);
		appendReferences(expire);
		expireService.saveExpire(expire);
		return JSONObject.parse(cmiPsonService.toJsonString(expireDAO.findExpireByPrimaryKey(expire.getId()), 2));
	}

	@RequestMapping(value = "/saveExpire", method = RequestMethod.PUT)
	@ResponseBody
	public Expire saveExpire(@RequestBody Expire expire) {
		expireService.saveExpire(expire);
		return expireDAO.findExpireByPrimaryKey(expire.getId());
	}

	@RequestMapping(value = "/restSaveExpire", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveExpire(@RequestBody String expireJson) {
		Expire expire = new Gson().fromJson(expireJson, Expire.class);
		appendReferences(expire);
		CmiPsonService cmiPsonService = new CmiPsonService();
		expireService.saveExpire(expire);
		return JSONObject.parse(cmiPsonService.toJsonString(expireDAO.findExpireByPrimaryKey(expire.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteExpire/{expireId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteExpire(@PathVariable Integer expireId) {
		Expire expire = expireDAO.findExpireByPrimaryKey(expireId);
		expireService.deleteExpire(expire);
	}

	@RequestMapping(value = "/restConfirmDeleteExpires")
	@ResponseBody
	public Object restConfirmDeleteExpires(@RequestBody Set<Integer> deleteExpiresIds) {
		Set<Expire> deleteExpires = expireDAO.findExpiresByIds(deleteExpiresIds);
		Set<Expire> referencedExpires = expireService.loadReferenceExpires(deleteExpires);
		deleteExpires.removeAll(referencedExpires);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedExpires);
		jsonObject.put("deleteEntitys", deleteExpires);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteExpires")
	@ResponseBody
	public Object restDeleteExpires(@RequestBody Set<Expire> deleteExpires) {
		Iterator<Expire> iterator = deleteExpires.iterator();
		while (iterator.hasNext()) {
			Expire currentExpire = iterator.next();
			expireService.deleteExpire(currentExpire);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listExpires");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadExpire/{expireId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadExpire(@PathVariable Integer expireId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(expireDAO.findExpireByPrimaryKey(expireId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadExpireUnit/{expireId}/unit", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadExpireUnit(@PathVariable Integer expireId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(expireDAO.findExpireByPrimaryKey(expireId).getUnit(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadExpireFoods/{expireId}/foods/{relatedfoodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadExpireFoods(@PathVariable Integer expireId, @PathVariable Integer relatedfoodId,
			@RequestBody CmiPagination cmiPagination) {
		Food food = foodDAO.findFoodByPrimaryKey(relatedfoodId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(food, 2, cmiPagination));
	}

	public void appendReferences(Expire expire) {

		Unit unit = expire.getUnit();
		if (unit != null)
			expire.setUnit(unitService.findUnitByPrimaryKey(unit.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Food> foodsForExpire = new HashSet<>();
		for (Food food_Expire : expire.getFoodsForExpire()) {
			foodsForExpire.add(foodService.findFoodByPrimaryKey(food_Expire.getId()));
		}
		expire.setFoodsForExpire(foodsForExpire);
	}

	@RequestMapping(value = "/restGetExpireUnit/{expireId}/unit", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetExpireUnit(@PathVariable Integer expireId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(expireDAO.findExpireByPrimaryKey(expireId).getUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetExpireFoods/{expireId}/foods", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetExpireFoods(@PathVariable Integer expireId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(expireDAO.findExpireByPrimaryKey(expireId).getFoodsForExpire(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restListExpires", method = RequestMethod.GET)
	@ResponseBody
	public Object restListExpires() {
		return JSONObject.parse(cmiPsonService.toJsonString(expireService.loadExpires(), 2));
	}

	@RequestMapping(value = "/restListExpiresPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListExpiresPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = expirePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Expire> expires = expireDAO.findAllExpires(startResult, cmiPagination.getPaginationSize());
		String expireString = cmiPsonService.toPsonString(expires, 2, cmiPagination);

		return JSONObject.parse(expireString);
	}

	@RequestMapping("/expireSelectBox")
	@ResponseBody
	public JSONObject expireSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Unit":
				entitySet = unitService.loadUnitsByIdSet(searchValue);
				break;

			// 被引用键
			case "Food":
				entitySet = foodService.loadFoodsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Unit":
				entitySet = unitDAO.findAllUnits((pageNumber - 1) * paginationSize, paginationSize);
				count = unitService.countUnits();
				break;

			// 被引用键
			case "Food":
				entitySet = foodDAO.findAllFoods((pageNumber - 1) * paginationSize, paginationSize);
				count = foodService.countFoods();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Unit":
				entitySet = unitDAO.findUnitByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = unitService.countUnitsByName(queryword);
				break;

			// 被引用键
			case "Food":
				entitySet = foodDAO.findFoodByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodService.countFoodsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
